package com.lalawaimai.plateform.order.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lalawaimai.palteform.baselib.base.BaseActivity;
import com.lalawaimai.palteform.baselib.http.CommonBean;
import com.lalawaimai.palteform.baselib.http.DisposeDataListener;
import com.lalawaimai.palteform.baselib.http.OkHttpException;
import com.lalawaimai.palteform.baselib.http.RequestWebInfo;
import com.lalawaimai.palteform.baselib.utils.CommonUtil;
import com.lalawaimai.palteform.baselib.utils.NullUtil;
import com.lalawaimai.palteform.baselib.widge.MyListView;
import com.lalawaimai.plateform.R;
import com.lalawaimai.plateform.bean.DeliveryerBean;
import com.lalawaimai.plateform.bean.DispatchBean;
import com.lalawaimai.plateform.bean.OrderDetailBean;
import com.lalawaimai.plateform.bean.OrderGoodsBean;
import com.lalawaimai.plateform.constant.Constant;
import com.lalawaimai.plateform.http.WebUrl;
import com.lalawaimai.plateform.order.adapter.OrderDetailAdapter;
import com.lalawaimai.plateform.order.fragment.WaitOrderFragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单详情页
 * Created by WaterWood on 2018/5/30.
 */
public class OrderDetailActivity extends BaseActivity implements View.OnClickListener {

    private TextView tv_title;
    private LinearLayout ll_back;
    private View status_bar;
    private String id;
    private TextView stroe_name;
    private TextView store_address;
    private TextView customer_info;
    private TextView customer_name;
    private TextView orderdetail_shopmobile;
    private TextView orderdetail_usermobile;
    private TextView send_time;
    private TextView number;
    private TextView orderdetail_mark;
    private TextView delivery_fee;
    private TextView box_fee;
    private TextView pack_fee;
    private TextView order_price;
    private TextView discount_fee;
    private TextView final_fee;
    private TextView order_sn;
    private TextView addtime;
    private TextView pay_type;
    private TextView assign_date;
    private TextView assign_time;
    private TextView instore_date;
    private TextView instore_time;
    private TextView takegoods_date;
    private TextView takegoods_time;
    private TextView success_date;
    private TextView success_time;
    private String status;
    private Button bt1;
    private Button bt2;
    private Button bt3;
    private Button bt4;
    private Button bt5;
    private Button bt6;
    private boolean isMore;
    private ProgressDialog dialogWeb;//网络加载等待框
    private TextView deliveryer_name;
    private RelativeLayout rl_deliveryer_info;
    private TextView tv_phone;
    private LinearLayout ll_deliveryer_title;
    private RelativeLayout callPhone;
    private String deliveryerPhone;
    private RelativeLayout callMap;
    private String longitude;//经度
    private String latitude;//纬度
    private String deliveryerName;//配送员名称
    private String order_takeout_num;//外卖单数
    private String order_errander_num;//跑腿单数
    private final int JUMP_MAP = 2;
    private MyListView listView;
    private List<OrderGoodsBean> listGoods;
    private OrderDetailAdapter mAdapter;

    @Override
    protected boolean initArgs(Bundle bundle) {
        id = bundle.getString("id");
        isMore = bundle.getBoolean("isMore", false);
        if (NullUtil.isStringEmpty(id)) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_order_detail;
    }

    @Override
    protected void initWidget() {
        //初始化控件
        tv_title = findViewById(R.id.tv_title);
        ll_back = findViewById(R.id.ll_back);
        stroe_name = findViewById(R.id.stroe_name);
        store_address = findViewById(R.id.store_address);
        customer_info = findViewById(R.id.customer_info);
        customer_name = findViewById(R.id.customer_name);
        orderdetail_shopmobile = findViewById(R.id.orderdetail_shopmobile);
        orderdetail_usermobile = findViewById(R.id.orderdetail_usermobile);
        send_time = findViewById(R.id.send_time);
        number = findViewById(R.id.number);
        orderdetail_mark = findViewById(R.id.orderdetail_mark);
        delivery_fee = findViewById(R.id.delivery_fee);
        box_fee = findViewById(R.id.box_fee);
        pack_fee = findViewById(R.id.pack_fee);
        order_price = findViewById(R.id.order_price);
        discount_fee = findViewById(R.id.discount_fee);
        final_fee = findViewById(R.id.final_fee);
        order_sn = findViewById(R.id.order_sn);
        addtime = findViewById(R.id.addtime);
        pay_type = findViewById(R.id.pay_type);
        assign_date = findViewById(R.id.assign_date);
        assign_time = findViewById(R.id.assign_time);
        instore_date = findViewById(R.id.instore_date);
        instore_time = findViewById(R.id.instore_time);
        takegoods_date = findViewById(R.id.takegoods_date);
        takegoods_time = findViewById(R.id.takegoods_time);
        success_date = findViewById(R.id.success_date);
        success_time = findViewById(R.id.success_time);
        deliveryer_name = findViewById(R.id.deliveryer_name);
        rl_deliveryer_info = findViewById(R.id.rl_deliveryer_info);
        tv_phone = findViewById(R.id.tv_phone);
        ll_deliveryer_title = findViewById(R.id.ll_deliveryer_title);
        callPhone = findViewById(R.id.callPhone);
        callMap = findViewById(R.id.callMap);
        listView = findViewById(R.id.listView);
        bt1 = findViewById(R.id.bt1);
        bt2 = findViewById(R.id.bt2);
        bt3 = findViewById(R.id.bt3);
        bt4 = findViewById(R.id.bt4);
        bt5 = findViewById(R.id.bt5);
        bt6 = findViewById(R.id.bt6);
        bt1.setOnClickListener(this);
        bt2.setOnClickListener(this);
        bt3.setOnClickListener(this);
        bt4.setOnClickListener(this);
        callPhone.setOnClickListener(this);
        callMap.setOnClickListener(this);
        //这里是对状态栏占位控件的设置，只要获取到控件调用这个方法就好。这是正常情况下都需要调用，但是如果是没有使用commonTitle的话，就不用这个了。
        status_bar = findViewById(R.id.status_bar);
        setStatusBarSize(this, status_bar);
        ll_back.setOnClickListener(this);
        tv_title.setText("订单详情");
        bt1.setVisibility(View.GONE);
        bt2.setVisibility(View.GONE);
        bt3.setVisibility(View.GONE);
        bt4.setVisibility(View.GONE);
        bt5.setVisibility(View.GONE);
        bt6.setVisibility(View.GONE);
        dialogWeb = CommonUtil.showProgressDialog(this, "正在加载");
        listGoods = new ArrayList<>();
        mAdapter = new OrderDetailAdapter(this,listGoods);
        listView.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_back:
                Intent intent = new Intent();
                intent.putExtra("back",1);
                setResult(RESULT_OK,intent);
                finish();
                break;
            case R.id.bt1:
                if (!status.equals("7")) {
                    //取消
                    Intent intent1 = new Intent(this, CancelReasonActivity.class);
                    startActivityForResult(intent1, WaitOrderFragment.CANCEL_REASON);
                } else {
                    //已退款
                    requestButton("refund_status", "");
                }
                break;
            case R.id.bt2:
                if (status.equals("1")) {
                    requestButton("notify_clerk_handle", "");
                } else if (status.equals("2") || status.equals("3")) {
                    requestButton("notify_deliveryer_collect", "");
                } else if (status.equals("4")) {
                    requestButton("re_notify_deliveryer_collect", "");
                } else if (status.equals("7")) {
                    requestButton("refund_query", "");
                }
                break;
            case R.id.bt3:
                if (status.equals("1")) {
                    requestButton("handle", "");
                } else if (status.equals("2") || status.equals("3")) {
                    diaodu();
                } else if (status.equals("4")) {
                    diaodu();
                } else if (status.equals("7")) {
                    requestButton("refund_handle", "");
                }
                break;
            case R.id.bt4:
                requestButton("end", "");
                break;
            case R.id.callPhone:
                CommonUtil.callPhone(this, deliveryerPhone);
                break;
            case R.id.callMap:
                Intent intent1 = new Intent(this, MapActivity.class);
                intent1.putExtra("longitude", longitude);
                intent1.putExtra("latitude", latitude);
                intent1.putExtra("deliveryerName", deliveryerName);
                intent1.putExtra("order_takeout_num", order_takeout_num);
                intent1.putExtra("order_errander_num", order_errander_num);
                startActivity(intent1);
                break;
        }
    }

    @Override
    protected void intiData() {
        dialogWeb.show();
        String url = WebUrl.GET_ORDER_DETAIL;
        Class<?> clazz = OrderDetailBean.class;
        List<String> list = new ArrayList<>();
        list.add("id");
        list.add("token");
        new RequestWebInfo(new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                dialogWeb.dismiss();
                String json = RequestWebInfo.jsonInfo;
                OrderDetailBean orderDetailBean = (OrderDetailBean) responseObj;
                stroe_name.setText(orderDetailBean.getMessage().getData().getStore().getTitle());
                store_address.setText(orderDetailBean.getMessage().getData().getStore().getAddress());
                customer_info.setText(orderDetailBean.getMessage().getData().getAddress());
                customer_name.setText(orderDetailBean.getMessage().getData().getUsername() + orderDetailBean.getMessage().getData().getSex() + " " + orderDetailBean.getMessage().getData().getMobile());
                orderdetail_shopmobile.setText(orderDetailBean.getMessage().getData().getStore().getTelephone());
                orderdetail_usermobile.setText(orderDetailBean.getMessage().getData().getMobile());
                send_time.setText(orderDetailBean.getMessage().getData().getDeliverytime_cn());
                number.setText("#" + orderDetailBean.getMessage().getData().getSerial_sn());
                orderdetail_mark.setText(orderDetailBean.getMessage().getData().getNote());
                delivery_fee.setText("￥" + orderDetailBean.getMessage().getData().getDelivery_fee());
                box_fee.setText("￥" + orderDetailBean.getMessage().getData().getBox_price());
                pack_fee.setText("￥" + orderDetailBean.getMessage().getData().getPack_fee());
                order_price.setText("￥" + orderDetailBean.getMessage().getData().getTotal_fee());
                discount_fee.setText("￥" + orderDetailBean.getMessage().getData().getDiscount_fee());
                final_fee.setText("￥" + orderDetailBean.getMessage().getData().getFinal_fee());
                order_sn.setText(orderDetailBean.getMessage().getData().getOrdersn());
                addtime.setText(orderDetailBean.getMessage().getData().getAddtime_cn());
                pay_type.setText(orderDetailBean.getMessage().getData().getPay_type_cn());
                assign_date.setText(orderDetailBean.getMessage().getData().getDelivery_assign_time_cn().getDay());
                assign_time.setText(orderDetailBean.getMessage().getData().getDelivery_assign_time_cn().getTime());
                instore_date.setText(orderDetailBean.getMessage().getData().getDelivery_instore_time_cn().getDay());
                instore_time.setText(orderDetailBean.getMessage().getData().getDelivery_instore_time_cn().getTime());
                takegoods_date.setText(orderDetailBean.getMessage().getData().getDelivery_takegoods_time_cn().getDay());
                takegoods_time.setText(orderDetailBean.getMessage().getData().getDelivery_takegoods_time_cn().getTime());
                success_date.setText(orderDetailBean.getMessage().getData().getDelivery_success_time_cn().getDay());
                success_time.setText(orderDetailBean.getMessage().getData().getDelivery_success_time_cn().getTime());
                if (orderDetailBean.getMessage().getData().getDeliveryer_id().equals("0")) {
                    rl_deliveryer_info.setVisibility(View.GONE);
                    ll_deliveryer_title.setVisibility(View.GONE);
                } else {
                    rl_deliveryer_info.setVisibility(View.VISIBLE);
                    ll_deliveryer_title.setVisibility(View.VISIBLE);
                    deliveryer_name.setText(orderDetailBean.getMessage().getData().getDeliveryer().getTitle());
                    tv_phone.setText(orderDetailBean.getMessage().getData().getDeliveryer().getMobile());
                    deliveryerPhone = orderDetailBean.getMessage().getData().getDeliveryer().getMobile();
                }
                longitude = orderDetailBean.getMessage().getData().getDeliveryer().getLocation_y();
                latitude = orderDetailBean.getMessage().getData().getDeliveryer().getLocation_x();
                deliveryerName = orderDetailBean.getMessage().getData().getDeliveryer().getTitle();
                order_takeout_num = orderDetailBean.getMessage().getData().getDeliveryer().getOrder_takeout_num();
                order_errander_num = orderDetailBean.getMessage().getData().getDeliveryer().getOrder_errander_num();
                status = orderDetailBean.getMessage().getData().getStatus();
                listGoods.clear();
                listGoods.addAll(orderDetailBean.getMessage().getData().getGoods());
                mAdapter.notifyDataSetChanged();
                //这里处理一下按钮的显示
                if (!isMore) {
                    if (status.equals("1")) {
                        bt1.setVisibility(View.VISIBLE);
                        bt2.setVisibility(View.VISIBLE);
                        bt3.setVisibility(View.VISIBLE);
                        bt1.setText("取消");
                        bt2.setText("通知商户");
                        bt3.setText("确定接单");
                    } else if (status.equals("2")) {
                        bt1.setVisibility(View.VISIBLE);
                        bt2.setVisibility(View.VISIBLE);
                        bt3.setVisibility(View.VISIBLE);
                        bt1.setText("取消");
                        bt2.setText("通知配送员");
                        bt3.setText("调度");
                    } else if (status.equals("3")) {
                        bt1.setVisibility(View.VISIBLE);
                        bt2.setVisibility(View.VISIBLE);
                        bt3.setVisibility(View.VISIBLE);
                        bt1.setText("取消");
                        bt2.setText("通知配送员");
                        bt3.setText("调度");
                    } else if (status.equals("4")) {
                        bt1.setVisibility(View.VISIBLE);
                        bt2.setVisibility(View.VISIBLE);
                        bt3.setVisibility(View.VISIBLE);
                        bt4.setVisibility(View.VISIBLE);
                        bt1.setText("取消");
                        bt2.setText("重置为代抢");
                        bt3.setText("调度");
                        bt4.setText("完成");
                    } else if (status.equals("7")) {
                        bt1.setVisibility(View.VISIBLE);
                        bt2.setVisibility(View.VISIBLE);
                        bt3.setVisibility(View.VISIBLE);
                        bt1.setText("已退款");
                        bt2.setText("查询退款进度");
                        bt3.setText("发起退款");
                    } else {
                        bt1.setVisibility(View.GONE);
                        bt2.setVisibility(View.GONE);
                        bt3.setVisibility(View.GONE);
                        bt4.setVisibility(View.GONE);
                        bt5.setVisibility(View.GONE);
                        bt6.setVisibility(View.GONE);
                    }
                } else {
                    bt1.setVisibility(View.GONE);
                    bt2.setVisibility(View.GONE);
                    bt3.setVisibility(View.GONE);
                    bt4.setVisibility(View.GONE);
                    bt5.setVisibility(View.GONE);
                    bt6.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                dialogWeb.dismiss();
                OkHttpException okHttpException = (OkHttpException) reasonObj;
                String msg = okHttpException.getEmsg().toString();
                if (msg.contains("java.net.ConnectException")) {
                    CommonUtil.showToast(OrderDetailActivity.this, "无法连接服务器，请检查您的网络");
                }else{
                    CommonUtil.showToast(OrderDetailActivity.this, msg);
                }
            }
        }).requestWeb(url, clazz, list, id,(String) CommonUtil.readData(OrderDetailActivity.this, Constant.TOKEN,Constant.STRING));
    }

    /**
     * 按钮的各种点击处理
     */
    private void requestButton(final String type, String reason) {
        dialogWeb.show();
        String url = WebUrl.REQUEST_BUTTON;
        Class<?> clazz = CommonBean.class;
        List<String> list = new ArrayList<>();
        list.add("token");
        list.add("id");
        list.add("type");
        if (type.equals("cancel")) {
            list.add("reason");
        }
        new RequestWebInfo(new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                dialogWeb.dismiss();
                CommonBean commonBean = (CommonBean) responseObj;
                CommonUtil.showToast(OrderDetailActivity.this, commonBean.getMessage().getResultMessage());
                intiData();
            }

            @Override
            public void onFailure(Object reasonObj) {
                dialogWeb.dismiss();
                OkHttpException okHttpException = (OkHttpException) reasonObj;
                String msg = okHttpException.getEmsg().toString();
                if (msg.contains("java.net.ConnectException")) {
                    CommonUtil.showToast(OrderDetailActivity.this, "无法连接服务器，请检查您的网络");
                }
            }
        }).requestWeb(url, clazz, list, (String) CommonUtil.readData(this, Constant.TOKEN,Constant.STRING),id, type, reason);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case WaitOrderFragment.CANCEL_REASON:
                    String reason = data.getStringExtra("reason");
                    requestButton("cancel", reason);
                    break;
                case JUMP_MAP:
                    intiData();
                    break;
            }
        }
    }

    /**
     * 调度方法
     */
    private void diaodu(){
        dialogWeb.show();
        String url = WebUrl.DIAPATCH;
        Class<?> clazz = DispatchBean.class;
        List<String> list = new ArrayList<>();
        list.add("id");
        list.add("token");
        new RequestWebInfo(new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                dialogWeb.dismiss();
                String json = RequestWebInfo.jsonInfo;
                DispatchBean dispatchBean = (DispatchBean) responseObj;
                List<DeliveryerBean> listDeliveryer = new ArrayList<>();
                for (int i=0;i<dispatchBean.getMessage().getData().getDeliveryers().size();i++){
                    DeliveryerBean deliveryerBean = new DeliveryerBean();
                    deliveryerBean.setName(dispatchBean.getMessage().getData().getDeliveryers().get(i).getTitle());
                    if (!NullUtil.isStringEmpty(dispatchBean.getMessage().getData().getDeliveryers().get(i).getLocation_x())) {
                        deliveryerBean.setLatitude(Double.parseDouble(dispatchBean.getMessage().getData().getDeliveryers().get(i).getLocation_x()));
                    }else{
                        continue;
                    }
                    if (!NullUtil.isStringEmpty(dispatchBean.getMessage().getData().getDeliveryers().get(i).getLocation_y())) {
                        deliveryerBean.setLongitude(Double.parseDouble(dispatchBean.getMessage().getData().getDeliveryers().get(i).getLocation_y()));
                    }else{
                        continue;
                    }
                    deliveryerBean.setOrder_errander_num(dispatchBean.getMessage().getData().getDeliveryers().get(i).getOrder_errander_num());
                    deliveryerBean.setOrder_takeout_num(dispatchBean.getMessage().getData().getDeliveryers().get(i).getOrder_takeout_num());
                    deliveryerBean.setId(dispatchBean.getMessage().getData().getDeliveryers().get(i).getId());
                    if (!NullUtil.isStringEmpty(dispatchBean.getMessage().getData().getLocation_x())) {
                        deliveryerBean.setLatitudeCustomer(Double.parseDouble(dispatchBean.getMessage().getData().getLocation_x()));
                    }else{
                        continue;
                    }
                    if (!NullUtil.isStringEmpty(dispatchBean.getMessage().getData().getLocation_y())) {
                        deliveryerBean.setLongitudeCustomer(Double.parseDouble(dispatchBean.getMessage().getData().getLocation_y()));
                    }else{
                        continue;
                    }
                    if (!NullUtil.isStringEmpty(dispatchBean.getMessage().getData().getStore().getLocation_x())) {
                        deliveryerBean.setLatitudeShop(Double.parseDouble(dispatchBean.getMessage().getData().getStore().getLocation_x()));
                    }else{
                        continue;
                    }
                    if (!NullUtil.isStringEmpty(dispatchBean.getMessage().getData().getStore().getLocation_y())) {
                        deliveryerBean.setLongitudeShop(Double.parseDouble(dispatchBean.getMessage().getData().getStore().getLocation_y()));
                    }else{
                        continue;
                    }
                    listDeliveryer.add(deliveryerBean);
                }
                //跳转到地图页面，然后显示相关内容
                Intent intent = new Intent(OrderDetailActivity.this, DispatchMapActivity.class);
                intent.putExtra("info",(Serializable) listDeliveryer);
                intent.putExtra("orderId",id);
                startActivityForResult(intent,JUMP_MAP);
            }

            @Override
            public void onFailure(Object reasonObj) {
                dialogWeb.dismiss();
                OkHttpException okHttpException = (OkHttpException) reasonObj;
                String msg = okHttpException.getEmsg().toString();
                if (msg.contains("java.net.ConnectException")) {
                    CommonUtil.showToast(OrderDetailActivity.this, "无法连接服务器，请检查您的网络");
                }
            }
        }).requestWeb(url, clazz, list, id,(String) CommonUtil.readData(this, Constant.TOKEN,Constant.STRING));
    }
}
